package com.xindacloud.sms.console.system.utils;

import com.xindacloud.sms.console.constant.SessionKeys;
import com.xindacloud.sms.console.system.entity.SmsUser;
import com.xindacloud.sms.console.system.exception.ServiceException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.function.Consumer;

public class UserSessionHelp {

    public static SmsUser getUserFromSession(HttpServletRequest request) {
        Object obj = request.getSession(false).getAttribute(SessionKeys.ACCOUNT);
        if (Objects.isNull(obj)) {
            throw new ServiceException("未找到会话信息.", UnionResultHelp.StatusEnum.FailToken.code());
        }
        return (SmsUser) obj;
    }

    public static Consumer<HttpHeaders> getHttpHeadersConsumer(HttpServletRequest request) {
        return httpHeaders -> {
            final SmsUser userFromSession = getUserFromSession(request);
            httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
            httpHeaders.set("username", userFromSession.getUsername());
            httpHeaders.set("password", userFromSession.getPassword());
        };
    }
}
